/*
 * Copyright 2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dopdf.document.hash.strategy;

import org.dopdf.document.read.DocumentReader;

import javax.servlet.http.HttpSession;

/**
 * The session based pdf fetching strategy saved the pdf documents in the http session.  This strategy could be used in
 * web applications where the number of documents being edited per session is not too many.
 * When the session is invalidated all the documents are cleared along with all other information held in the session.
 *
 * @author Deep Shah
 */
public class SessionBasedDocumentHashingStrategy implements DocumentHashingStrategy {
    /** The http session reference. */
    private HttpSession httpSession;

    /** The identifier generator used by this strategy. */
    private IdentifierGenerator identifierGenerator;

    /**
     * The constructor that takes in the http session as argument.  This will then be used to save and fetch the pdf
     * documents when required.
     * @param httpSession the session reference used to save and fetch the pdf documents.
     * @param identifierGenerator the identifier generator to use with this type of fetching strategy.
     */
    public SessionBasedDocumentHashingStrategy(final HttpSession httpSession,
                                               final IdentifierGenerator identifierGenerator) {
        this.httpSession = httpSession;
        this.identifierGenerator = identifierGenerator;
    }

    /**
     * Puts the pdf document in the session and returns the identifier for that pdf document.
     * {@inheritDoc}
     * @param documentReader
     */
    public String hash(final DocumentReader documentReader) {
        final String key = identifierGenerator.generateUniqueId();
        httpSession.setAttribute(key, documentReader);
        return key;
    }

    /**
     * {@inheritDoc}
     */
    public DocumentReader unHash(final String key) {
        return (DocumentReader) httpSession.getAttribute(key);
    }
}
